package com.luchao.springboot.springbootsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 *权限配置类
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                authorizeRequests()
                    .antMatchers("/", "/home").permitAll()  // 设置所有人都可以访问登录页面
                    .anyRequest()    // 任何请求,登录后可以访问
                    .authenticated()
                    .and()
                .formLogin()        // 定义当需要用户登录时候，转到的登录页面。
                    .loginPage("/login").permitAll()  // 设置登录请求
                    //.loginProcessingUrl("/user/login")  // 自定义的登录接口
                    .and()
                .logout()
                    .permitAll();
                //关闭默认的csrf认证
                http.csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中添加用户,不加passwordEncoder会报错。
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
        //.passwordEncoder(new MyPasswordEncoder())。
        //这样，页面提交时候，密码以明文的方式进行匹配。
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("zhaolu").password("zhaolu").roles("ADMIN");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置静态资源不要拦截
        web.ignoring().antMatchers("/static/**","/js/**","/cs/**","/images/**");
    }

}
